package org.dbstar.scheduler.ldap;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class SchedulerUserDetailsService implements UserDetailsService {
	private UserDetailsService service;

	public SchedulerUserDetailsService(UserDetailsService service) {
		super();
		this.service = service;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		UserDetails user = service.loadUserByUsername(username);

		SchedulerUserDetails details = new SchedulerUserDetails();
		details.setUsername(username);
		details.setDisplayName(StringUtils.substringBefore(username,"@"));
		details.setPassword(user.getPassword());

		// Add the supplied authorities
		if (user.getAuthorities() == null || user.getAuthorities().isEmpty()) {
			details.addAuthority(new SimpleGrantedAuthority("ANONYMOUS"));
		} else {
			for (GrantedAuthority authority : user.getAuthorities()) {
				details.addAuthority(authority);
			}
		}

		return details;
	}
}
